<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/7
 * Time: 下午4:22
 */

namespace App\Utils;


use App\Models\FormIds;
use App\Models\Users;
use App\User;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class MiniProgramUtil
{
    const TEMPLATE_COMMIT_NOTICE = 1;

    private $app;

    public function __construct($name = '')
    {
        $this->app = EasyWeChat::miniProgram($name);
    }

    public function getApp()
    {
        return $this->app;
    }

    /**
     * code解析
     * @param $code
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    public function authSession($code)
    {
        return $this->app->auth->session($code);
    }

    /**
     * 解密
     * @param $sessionKey
     * @param $iv
     * @param $encrypted
     * @return array
     */
    public function decryptData($sessionKey, $iv, $encrypted)
    {
        //解密手机号码正确返回的数据格式
        //$result['purePhoneNumber'], $result['countryCode']);

        //解密用户信息
        //        {
        //            "openId": "o_xV75eRlb0PBWbpjyix7HMNMEKc",
        //            "nickName": "流年",
        //            "gender": 1,
        //            "language": "zh_CN",
        //            "city": "Shenzhen",
        //            "province": "Guangdong",
        //            "country": "China",
        //            "avatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/ttdKiaybrdOA57eVvA9Hicy5xE8t7CPqpKJ68wicPUYXiata4lgD9b1tZvqnnVWLsSWribhJibZakUsia2g4DjhtC29vQ/132",
        //            "unionId": "oNESR0gPIbyWobH8XtJIIcteZ4bs",
        //            "watermark": {
        //            "timestamp": 1532418247,
        //                "appid": "wx03428e02d74df1af"
        //            }
        //        }

        return $this->app->encryptor->decryptData($sessionKey, $iv, $encrypted);
    }


    /**
     * 获取无限制的小程序二维码
     * @param $scene
     * @param string $page
     * @return string
     */
    public function getAppCodeUnlimit($scene, $page = '')
    {
        $option = [
            'page' => $page
        ];

        $fileContent = $this->app->app_code->getUnlimit($scene, $option);
        $qiniuUtil = new QiniuUtil();
        $url = $qiniuUtil->uploadBase64($fileContent);

        return $url;
    }

    /**
     * 获取小程序临时图片素材的mediaId
     * @param string $type
     * @return bool|mixed
     */
    public function getTempImageMediaId($type = 'customer_service')
    {
        switch($type){
            case 'customer_service':
                $image = 'images/qrcode.jpg';
                $time = 3600 * 24 * 2;
                break;
            default:
                return false;
                break;
        }
        $cacheKey = 'mini_program_image_' . $type;

        $value = Cache::get($cacheKey);
        if (!empty($value)){
            return $value;
        }

        $mediaInfo = $this->app->media->upload('image', public_path($image));
        if (isset($mediaInfo['media_id'])){
            Cache::put($cacheKey, $mediaInfo['media_id'], $time);

            return $mediaInfo['media_id'];
        }

        return false;
    }


    public function studyNotice(Users $user, $templateId)
    {
        $templateData = [
            'touser' => $user->open_id,
            'template_id' => $templateId,
            'page' => 'pages/index/index',
            'form_id' => 'form-id',
            'data' => [],
        ];

        switch($templateId){
            case 'Rb-rOZkClqGPbqmf5dDGkk4DD4yqZvo4QAwlp61-95I':
                $templateData['data'] = [//每日练习通知
                    'thing4.DATA' => '练习内容',//练习内容
                    'thing2.DATA' => '温馨提醒',//温馨提醒
                ];
                break;
            case 'Rb-rOZkClqGPbqmf5dDGkisvWD0pRpT9z7tJNQvB1R4':
                $templateData['data'] = [//每日练习通知
                    'thing4.DATA' => '练习内容',//练习内容
                    'thing5.DATA' => '练习时间',//练习时间
                    'thing2.DATA' => '温馨提醒',//温馨提醒
                ];
                break;
            case 'a1xdDSsqbtCojMVikbvHBUp67SpAjHdo9_4l-50RWtA':
                $templateData['data'] = [//记忆清单复习提醒
                    'thing1.DATA' => '清单内容',//清单内容
                    'thing3.DATA' => '温馨提示',//温馨提示
                ];
                break;
            case 'a1xdDSsqbtCojMVikbvHBdIX2xphWMY49wVj89x4ceo':
                $templateData['data'] = [//记忆清单复习提醒
                    'thing1.DATA' => '清单内容',//清单内容
                    'thing2.DATA' => '复习日期',//复习日期
                    'thing3.DATA' => '温馨提示',//温馨提示
                ];
                break;
            default:
                break;
        }


        try{
            $result = $this->app->template_message->send($templateData);

        }catch(\Exception $exception){
            Log::info('===send_template_error===' . $exception->getMessage() . '===' . json_encode($templateData));

            return false;
        }

    }

    /**
     * 通知
     * @param \App\User $user
     * @return array|bool|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    public function commentNotice(User $user)
    {
        $templateId = self::TEMPLATE_COMMIT_NOTICE;


        $page = 'pages/index/index';

        $data = [
            $user->nick_name,
            date('Y-m-d H:i:s'),
            '你收到一条买卖留言，去看看吧'
        ];

        return $this->send($user->id, $user->open_id, $templateId, $data, $page);

    }

    /**
     * 发送
     * @param $userId
     * @param $openId
     * @param $templateId
     * @param $data
     * @param string $page
     * @return array|bool|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    private function send($userId, $openId, $templateId, $data, $page = 'index')
    {
        $template = self::getTemplateData($templateId, $data);
        if ($template === false){
            return false;
        }else{
            $templateId = $template['templateId'];
            $data = $template['data'];
        }

        $templateMessage = [
            'touser' => $openId,
            'template_id' => $templateId,
            'page' => $page,
            'form_id' => '',
            'data' => $data,
            'emphasis_keyword' => $template['emphasis_keyword'],
        ];

        if (empty($templateMessage['emphasis_keyword'])){
            unset($templateMessage['emphasis_keyword']);
        }

        try{
            $result = $this->app->template_message->send($templateMessage);

        }catch(\Exception $exception){
            Log::info('===send_template_error===' . $exception->getMessage() . '===' . json_encode($templateMessage));

            return false;
        }


        return $result;
    }

    /**
     * 模板列表
     * @param $templateId
     * @param $data
     * @return array|bool
     */
    private static function getTemplateData($templateId, $data)
    {
        $list = [
            self::TEMPLATE_COMMIT_NOTICE => [//已关注问题回复提醒
                'templateId' => '_SvH9s6wA1rGa_11S2coRM8rdb01reBOnGYqh8bcBLY',
                'data' => [
                    '回复人',//小李
                    '回复时间',//2018-3-8
                    '备注' => '您关注的问题已被处理'
                ],
                //'emphasis_keyword' => 'keyword1.DATA',
            ],

        ];

        if (isset($list[$templateId]) && count($list[$templateId]['data']) == count($data)){
            $keywords = [];
            foreach($data as $key => $value){
                $color = '#173177';
                $keywords['keyword' . ($key + 1)] = [
                    $value,
                    $color
                ];
            }

            $template = $list[$templateId];
            $template['data'] = $keywords;

            return $template;
        }

        return false;
    }

    public function generateScheme($path, $query)
    {
        try{

            $client = new Client();

            $url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $this->app->access_token->getToken()['access_token'];
            $response = $client->request('POST', $url, ['json' => ['jump_wxa' => ['path' => $path, 'query' => $query]]]);

            return $response->getBody();

        }catch(\Exception $exception){


            return false;
        }
    }

    public function userRisk($data)
    {
        try{
            $data['appid'] = env('WECHAT_MINI_PROGRAM_APPID');
            $data['scene'] = 0;

            $client = new Client();

            $url = 'https://api.weixin.qq.com/wxa/getuserriskrank?access_token=' . $this->app->access_token->getToken()['access_token'];
            $response = $client->request('POST', $url, ['json' => $data]);

            return $response->getBody();

        }catch(\Exception $exception){


            return false;
        }
    }

    public function mobileByCode($code)
    {
        try{
            $data['code'] = $code;

            $client = new Client();

            $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $this->app->access_token->getToken()['access_token'];
            $response = $client->request('POST', $url, ['json' => $data]);

            $body = json_decode($response->getBody(), true);

            Log::info('手机号', [$body]);

            return $body;

        }catch(\Exception $exception){


            return false;
        }
    }

}
